package com.xjoyt.pay.share.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.share.dao.BankRepositoryCustom;
import com.xjoyt.pay.share.params.BankPageParam;
import com.xjoyt.pay.share.po.Bank;
import com.xjoyt.pay.share.repository.BankRepository;

public class BankRepositoryImpl extends AbstractDao implements BankRepositoryCustom {

	@Autowired
	private BankRepository repository;

	@Override
	public PageResult<Bank> loadPage(PageParam<BankPageParam> param) {
		Pageable pageable = getPageable(param);
		Specification<Bank> spec = getSpecification(param.query);
		Page<Bank> pageReuslt = repository.findAll(spec, pageable);
		return new PageResult<>(pageReuslt.getTotalElements(), pageReuslt.getContent());
	}

	private Specification<Bank> getSpecification(BankPageParam param) {
		Specification<Bank> spec = (root, query, cb) -> {
			if (param == null) {
				return null;
			}
			List<Predicate> list = new ArrayList<>();
			if (StringUtils.isNotBlank(param.query)) {
				for (String string : param.query.split(" ")) {
					if (StringUtils.isBlank(string))
						continue;
					String like = "%" + string + "%";
					list.add(cb.or(cb.like(root.get("bankChannelNo"), like), cb.like(root.get("bankName"), like)));
				}
			}
			if (CollectionUtils.isNotEmpty(list))
				query.where(cb.and(list.toArray(new Predicate[list.size()])));

			return null;
		};
		return spec;
	}
}
